import { Project } from '../entities/project'
import { ProjectUnit } from '../entities/project-unit'

const resolver = {
  Query: {
    projects: async (root, args, { db }, info) => {
      const query = await db.getRepository(Project)
        // .createQueryBuilder('project')
        // .leftJoinAndSelect('project.units', 'unit')
        // .getMany()
        .find({ relations: ['units'] })

      return query
    },
  },

  Mutation: {
    async createProject (root, args, { db }, info) {
      const { createProjectInput: { name, units } } = args

      const projectUnits = units.map(unit => {
        const projectUnit = new ProjectUnit()
        console.log(unit)
        projectUnit.status = unit.status
        projectUnit.startTime = new Date(unit.startTime).toString()
        projectUnit.endTime = new Date(unit.endTime).toString()
        projectUnit.owner = unit.owner

        return projectUnit
      })

      const projectUnitsRepo = await db.getRepository(ProjectUnit)
      await projectUnitsRepo.save(projectUnits)

      const project = new Project()
      project.name = name
      project.units = projectUnits

      const repo = await db.getRepository(Project)
      await repo.save(project)

      return {
        success: true,
      }
    },

    async deleteProject (root, args, { db }, info) {
      try {
        const { id } = args
        console.log(id)
        await db.getRepository(ProjectUnit).delete({ projectId: id })
        await db.getRepository(Project).delete({ id })
        return {
          success: true,
        }
      } catch (error) {
        console.log(error)
        return {
          success: false,
        }
      }
    },

    async updateProject (root, args, { db }, info) {
      try {
        const { id, updateProjectInput: { name, units } } = args

        units.forEach(async unit => {
          const { status, ...rest } = unit
          await db.getRepository(ProjectUnit)
            .createQueryBuilder()
            .update()
            .set(rest)
            .where('status= :status', { status })
            .execute()
        })

        await db.getRepository(Project)
          .createQueryBuilder()
          .update()
          .set({ name })
          .where('id= :id', { id})
          .execute()
        return {
          success: true,
        }
      } catch (error) {
        return {
          success: false,
        }
      }
    }
  },
}

export default resolver
